/**
 * Safely retrieves a value from a nested object using a path string.
 * Handles paths with dot notation and bracket notation for array indices.
 *
 * Example paths: 'a.b', 'a[0].c', '[1]', 'data.items[2].name'
 *
 * @param obj The object to retrieve the value from.
 * @param path The path string.
 * @returns The value found at the path, or undefined if the path is invalid or the value doesn't exist.
 */
export function getValueFromPath(obj: any, path: string | null | undefined): any {
    // Basic validation for input
    if (path === '') {
        // An empty string path explicitly means return the root object.
        return obj;
    }
    if (path === null || path === undefined) {
        // If the path itself is null or undefined, treat it as invalid for lookup.
        // console.warn(`[getValueFromPathV2] Received null or undefined path. Returning undefined.`);
        return undefined;
    }

    try {
        // Improved Regex: Match property names (including those with dashes if needed),
        // or bracketed indices (numeric or potentially quoted strings if needed later).
        // This version focuses on alphanumeric property names and numeric indices.
        const parts = path.match(/([a-zA-Z0-9_$]+)|\[(\d+)\]/g);
        // Example: 'a.b[0][1].c' -> ['a', 'b', '[0]', '[1]', 'c']

        // <<< NEW: Check if the first part is an array index and if the obj is actually an array >>>
        if (parts && parts.length > 0 && parts[0].startsWith('[') && parts[0].endsWith(']')) {
            if (!Array.isArray(obj)) {
                console.warn(`[getValueFromPathV2] Path "${path}" starts with an index, but the provided object is not an array.`);
                return undefined;
            }
        }
        // <<< END NEW CHECK >>>

        if (!parts) {
            // Handle cases where the path is just a simple key without dots/brackets
            if (path in obj) {
                return obj[path];
            } else {
                 console.warn(`[getValueFromPathV2] Path "${path}" could not be parsed into parts or key does not exist.`);
                 return undefined;
            }
        }

        let current: any = obj;
        for (const part of parts) {
            if (current === null || current === undefined) {
                // Cannot drill down further if current value becomes null/undefined
                return undefined;
            }

            let key: string | number;
            if (part.startsWith('[') && part.endsWith(']')) {
                // Array index like "[0]"
                key = parseInt(part.substring(1, part.length - 1), 10);
                if (isNaN(key)) {
                    console.warn(`[getValueFromPathV2] Invalid array index found in path "${path}": ${part}`);
                    return undefined;
                }
                // Check if current is actually an array before indexing
                if (!Array.isArray(current)) {
                    console.warn(`[getValueFromPathV2] Attempted to index non-array with index ${key} in path "${path}". Current value:`, current);
                    return undefined;
                }
            } else {
                // Object key like "propertyName"
                key = part;
            }

            // Check if the key/index exists in the current object/array
            // Using 'in' operator works for both object properties and array indices
            if (!(key in current)) {
                // Optionally provide more context in the warning
                // console.warn(`[getValueFromPathV2] Key/Index "${key}" (from part "${part}") not found in path "${path}". Current object/array:`, current);
                return undefined; // Key/index doesn't exist
            }

            // Move to the next part of the path
            current = current[key];
        }

        // Return the final value found at the end of the path
        return current;

    } catch (error) {
        // Catch potential errors during property access (though checks should prevent most)
        console.error(`[getValueFromPathV2] Unexpected error accessing path "${path}":`, error);
        return undefined;
    }
} 